<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/6
 * Time: 12:02
 */

namespace app\api\service;


use app\lib\Exception\TokenException;
use app\lib\Exception\WxException;
use think\Cache;
use think\Exception;

class AccessToken
{
    protected $url;
    const ACCESS_TOKEN_KEY = 'ACCESS';
    const ACCESS_TOKEN_EXPIRE = 7000;

    function __construct()
    {
        $appID = config('wx.app_id');
        $appSecret = config('wx.app_secret');
        $this->url = sprintf(config('wx.access_token_url'), $appID, $appSecret);
    }

    public function get(){
       $result =  $this->getFromCache();

       if(!$result){
           return $this->getFromWx();
       } else{
        return $result;
       }
    }

    private function getFromCache(){
        $vars = Cache::get(self::ACCESS_TOKEN_KEY);
        if($vars){
            return $vars;
        }

        return false;
    }

    private function getFromWx()
    {
        // json
        $result = curl_get($this->url);

        // json转换为array
        $result = json_decode($result, true);

        if (empty($result)) {
            throw new Exception('获取session_key及openID异常，微信内部错误');
        } else {
            $errorExist = key_exists('errcode', $result);
            if ($errorExist) {
                // 出现错误
                throw new WxException([
                    'info'=>$result['errmsg'],
                    'errorCode'=>$result['errcode']
                ]);
            } else {
                $this->saveToCache($result['access_token']);
                return $result['access_token'];
            }
        }
    }

    private function saveToCache($token){
        $result = cache(self::ACCESS_TOKEN_KEY, $token,self::ACCESS_TOKEN_EXPIRE);
        if(!$result){
            // 缓存出错
            throw new TokenException([
                'info'=>'服务器缓存异常',
                'errorCode'=>10005
            ]);
        }
    }
}